"use client";

import "@chatui/core/dist/index.css";
import Chat, { Bubble, useMessages } from "@chatui/core";
import { useEffect, useRef, useState } from "react";
import { nanoid } from "nanoid";
import MdViewer from "@/components/MdViewer";

/**
 * 聊天室组件
 * @constructor
 */
const ChatCard = () => {
    const { messages, appendMsg, setTyping, updateMsg } = useMessages([{
        _id: nanoid(),
        type: "text",
        content: { text: "你好！我是你的智能助手，有什么我可以帮你的吗？" },
    }]);
    const [msgID, setMsgID] = useState("");
    const [result, setResult] = useState("");
    const socket = useRef<WebSocket | null>(null);
    const sessionMsg = useRef("");
    const msgBuffer = useRef("");
    const hasGreeted = useRef(false); // 用于防止重复问候

    useEffect(() => {
        // 只在首次加载时显示问候语
        if (!hasGreeted.current) {
            appendMsg({
                type: "text",
                content: { text: "你好！我是你的智能助手，有什么可以帮你的吗？" },
            });
            hasGreeted.current = true;
        }
    }, [appendMsg]);

    useEffect(() => {
        // 更新 message（模拟打字机效果）
        if (msgID) {
            updateMsg(msgID, {
                type: "text",
                content: { text: result },
            });
        }
    }, [result, msgID, updateMsg]);

    useEffect(() => {
        const wsUrl = `ws://localhost:8101/api/ws/chat`;
        socket.current = new WebSocket(wsUrl);

        socket.current.addEventListener("open", () => {
            console.log("WebSocket 连接已打开");
        });

        socket.current.addEventListener("message", (event) => {
            console.log("收到服务器消息:", event.data);
            if (event.data === "[DONE]") {
                sessionMsg.current += "\n";
            } else {
                msgBuffer.current += event.data;
                setResult(msgBuffer.current);
                sessionMsg.current += event.data;
            }
        });

        socket.current.addEventListener("close", () => {
            console.log("WebSocket 连接已关闭");
        });

        socket.current.addEventListener("error", (err) => {
            console.error("WebSocket 出现错误:", err);
        });

        return () => {
            // 组件卸载时关闭连接
            if (socket.current) {
                socket.current.close();
            }
        };
    }, []);

    function handleSend(type: string, val: string) {
        if (type === "text" && val.trim()) {
            const newMsgId = nanoid();
            setMsgID(newMsgId);

            appendMsg({
                type: "text",
                content: { text: val },
                position: "right",
            });

            msgBuffer.current = "";
            setResult("");

            sessionMsg.current += val + "\n";
            appendMsg({
                _id: newMsgId,
                type: "text",
                content: { text: "" },
            });

            if (socket.current && socket.current.readyState === WebSocket.OPEN) {
                socket.current.send(sessionMsg.current);
            } else {
                console.error("WebSocket 未连接");
            }
        }
    }

    function renderMessageContent(msg: any) {
        const { content } = msg;
        // eslint-disable-next-line react/no-children-prop
        return <Bubble children={<MdViewer value={content.text} />} />;
    }

    return (
        <div className="chatcard">
            <Chat
                navbar={{ title: "智能助理" }}
                messages={messages}
                renderMessageContent={renderMessageContent}
                onSend={handleSend}
            />
        </div>
    );
};

export default ChatCard;